#! /usr/bin/env python

#  Given prefixes to filenames, assumes they're rows of k1, k2, k3, k4,
# and produces a single list of average k1, k2, k3, k4

import sys, os
import numpy

path = "trials/"
outpath = "analysis/"

number_of_each_file = 1000
n = number_of_each_file
lines_per_file = 20
"""
prefixes = ["source_0.1_present",
            "source_1.0_present",
            "source_10.0_present",
            "source_100.0_present",
            "source_1000.0_present",
            "source_absent"]
"""

prefixes = ["source_1.0_present", "source_absent"]

if sys.argv[1] == 'k':
	for prefix in prefixes:
		output_mean = outpath + prefix + "_mean.txt"
		output_var  = outpath + prefix + "_var.txt"
		output_mean_contents = ""
		output_var_contents = ""
		arr = numpy.empty((number_of_each_file, lines_per_file, 5))
		for i in range(n):
			f = open(path + prefix + str(i) + ".txt", "r")
			contents = f.readlines()
			for j in range(len(contents)):
				contents[j] = contents[j].split()
			arr[i] = numpy.array(contents)
			f.close()
		means = arr.mean(0)
		vars  = arr.var(0)
		for k in range(len(means)):
			output_mean_contents += str((k+1)*3) + " %s %s %s %s %s\n" \
									% tuple(means[k])
			output_var_contents += str((k+1)*3) + " %s %s %s %s %s\n" \
									% tuple(vars[k])
		f = open(output_mean, "w")
		f.write(output_mean_contents)
		f.close()
		f = open(output_var, "w")
		f.write(output_var_contents)
		f.close()

elif sys.argv[1] == 's':
	for prefix in prefixes:
		output_mean = prefix + "_mean"
		output_var  = prefix + "_var"
		output_mean_contents = ""
		output_var_contents = ""
		arr = numpy.empty((number_of_each_file, lines_per_file, 3))
		for i in range(n):
			f = open(path + prefix + str(i), "r")
			contents = f.readlines()
			for j in range(len(contents)):
				contents[j] = contents[j].split()
			arr[i] = numpy.array(contents)
		means = arr.mean(0)
		vars  = arr.var(0)
		for k in range(len(means)):
			output_mean_contents += "%s\t%s\t%s\n" % tuple(means[k])
			output_var_contents  += "%s\t%s\t%s\n" % tuple(vars[k])
		f = open(output_mean, "w")
		f.write(output_mean_contents)
		f.close()
		f = open(output_var, "w")
		f.write(output_var_contents)
		f.close()
else:
	print "no can do, boss"
